<?php
// +----------------------------------------------------------------------
// | layerIM + Workerman + ThinkPHP5 即时通讯
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\index\controller;

use think\Controller;
use think\Config;
use think\Session;
use app\api\controller\Uploads;
use app\common\model\Images as ImagesModel;

class Test extends Controller
{
    protected $images_model;

    protected function _initialize(){
        parent::_initialize();
        $this->images_model = new ImagesModel();
    }
    public function shall(){

        return $this->hello(function ($data=0){
            return 'shall data';
        });
    }

    public function hello(){
        return 'hello';
    }
    public function index()
    {
        return $this->fetch();
    }
	public function now(){
		echo date("Y-m-d H:i:s",time());
		echo '</br>';
		echo date("H:i:s",time());
		echo 'hello';
	}

    public function upload()
    {
        //$file = request()->file('file');
        //dump($file);
        return json(['code' => 1, 'data' => '', 'msg' => 'success']);
    }

    public function author(){
        $wechat = $this->config;
        $wechat_author = $this->wechat_author_util;
        $author_code = $wechat_author->getPreAuthCode();
        $redirect_uri = 'https://sn.shangning.site/index/test/savewxuser';
        //引导授权页
        $author_url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.$wechat['appid'].'&pre_auth_code='.$author_code['pre_auth_code'].'&redirect_uri='.$redirect_uri.'&auth_type=3';
        $this->redirect($author_url);
    }

    /**
     * @param auth_code 授权码
     * @param expires_in 过期时间
     */
    public function savewxuser($auth_code,$expires_in){
        $wechat_author = $this->wechat_author_util;
        $query_auth = $wechat_author->query_auth($auth_code);

        $wechat_info = $query_auth['authorization_info'];
        $authors = $query_auth['authorization_info']['func_info'];

        //获取授权公众号基本信息
        $base_info = $wechat_author->getAuthorizerInfo($wechat_info['authorizer_appid']);
        $wechat_base_info = $base_info['authorizer_info'];

        $data = [
            'appid'                    => $wechat_info['authorizer_appid'], //公众号appid
            'wxname'                   => $wechat_base_info['nick_name'],   //微信公众号名字
            'headerpic'                => $wechat_base_info['head_img'], //微信公众号头像
            'type'                     => $wechat_base_info['service_type_info']['id'], //微信公众号类型
            'verify_type'              => $wechat_base_info['verify_type_info'], //授权方认证类型
            'wxid'                     => $wechat_base_info['user_name'], //原始id
            'weixin'                   => $wechat_base_info['alias'], //微信号
            'qr'                       => $wechat_base_info['qrcode_url'], //二维码图片的URL
            'idc'                      => $wechat_base_info['idc'],
            'principal_name'           => $wechat_base_info['principal_name'], //公众号的主体名称
            'signature'                => $wechat_base_info['signature'], //公众号的主体名称
            'authorizer_access_token'  => $wechat_info['authorizer_access_token'], //授权方接口调用凭据
            'authorizer_expires'       => time() + $expires_in - 200, // 提前200秒过期
            'authorizer_refresh_token' => $wechat_info['authorizer_refresh_token'], //接口调用凭据刷新令牌
            'business_info'            => serialize($wechat_base_info['business_info']), //功能
            'funcscope_category'       => serialize($authors), //授权给开发者的权限集列表
        ];

        $result = $this->author_wx_user->allowfield(true)->save($data);

        if($result){
            $this->redirect(url('admin/publicnum/index'));
        }else{
            $this->error('绑定失败');
        }
    }

    public function test(){
        return $this->fetch();
    }

    public function testapi(){
        $file = $this->request->file('files');
        if($file){
            $upload = new Uploads();
            $upload_result = $upload->upload($file);
            if($upload_result['error'] == 0){
                $data = $this->request->param();
                if(!is_dir('./uploads/sucai/'.$data['pid'])){
                    mkdir('./uploads/sucai/'.$data['pid']);
                }
                $image = \think\Image::open('.'.$upload_result['url']);
                $height = $image->height();
                $filename = '/uploads/sucai/'.$data['pid'].'/'.date('YmdHis').'_'.$data['pid'].rand(100,9999).'_thumb.png';
                if($height > 400 ){
                    $image->water('./static/images/sy.png',1)->save('.'.$filename);
                }else{
                    $image->water('./static/images/xsy.png',1)->save('.'.$filename);
                }
                $data['path'] = $upload_result['url'];
                $data['thumb'] = $filename;
                $data['user_id'] = session::get('index_id');

                $result = $this->images_model->allowField(true)->save($data);
                if($result){
                    $this->success('保存成功');
                }else{
                    $this->error('保存失败');
                }
            }
        }
    }


    public function testcustomchat(){
        $wechatObj = $this->wechatObj;
        $result = $wechatObj->getSessiOnlist();
        dump($result);
    }

    //二维码
    public function qrcode(){
        $data = $this->qrcode_model->where('auid',7)->where('is_open',1)->value('media_ids');
        $media_ids = [];
        if($data){
            $media_ids = unserialize($data);
        }
        dump(1);
        dump(empty($media_ids));
    }

    public function socket(){
        // 文本加一个回车
        // $buffer1 = 'abcdefghijklmn
        // ';
        // 在php中双引号中的\n代表一个换行符，例如"\n"
        $buffer2 = '{"type":"chatMessage","data":{"mine":{"id":"20","username":"xiaoyu","avatar":"/uploads/20180425/ef30e1b96b0999f62bbe49110f42cc0f.jpg", "content":"你好啊!!"},"to":{"type":"friend","id":"21"}}}'."\n";
        // $buffer2 = '{"type":"init","id":"20","username":"xiaoyu","avatar":"/uploads/20180425/ef30e1b96b0999f62bbe49110f42cc0f.jpg","sign":"qwe"}'."\n";
        // $buffer2 = '{"type":"init","username":"xiaoyu","avatar":"/uploads/20180425/ef30e1b96b0999f62bbe49110f42cc0f.jpg","sign":"qwe"}'."\n";
        echo $buffer2;
        // 与服务端建立socket连接
        $client = stream_socket_client('tcp://127.0.0.1:8383', $errno, $errstr);
        fwrite($client, $buffer2);
    }

    public function request(){
        // $csuser = M('csuser')->where('auid',32)->find();

        $post_arr = ['content'=>'你好','openid'=>'ouW8T0t-nV4GjaSCwbcGMSU0Vgdc','appid'=>'wx684cccbe844d934c','cs_id'=>5];
        // $post = json_encode($post_arr , JSON_UNESCAPED_UNICODE);
        $return = httpRequest('https://a.cnshuangqing.cn/receiveMsg','POST',$post_arr);
        file_put_contents('./requestMsg.log',$return);
    }

    public function login(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $result = M('csuser')->where('username',$data['username'])->where('password',md5($data['pwd'] . Config::get('salt')))->find();
            if($result){
                return json_encode(['status'=>1,'msg'=>'登录成功','user_info'=>$result],JSON_UNESCAPED_UNICODE);
            }else{
                return json_encode(['status'=>-1,'msg'=>'登录失败'],JSON_UNESCAPED_UNICODE);
            }
        }else{
            return json_encode(['msg'=>'你妹'],JSON_UNESCAPED_UNICODE);
        }
    }

    public function getUserInfo($appid,$openid){
        $author_wx = M('author_wx_user')->where('appid',$appid)->where('authorized',1)->find();
        $wechatObj = new WechatThirdUtil($this->config , $author_wx);
        $result = $wechatObj->getFanInfo($openid);
        return json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    public function getUserInfo2($openid){
        $result = M('users')->where('openid',$openid)->find();
        return json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    public function sengMsgForUser(){
        // $appid = 'wx684cccbe844d934c';
        // $openid = 'ouW8T0t-nV4GjaSCwbcGMSU0Vgdc';
        // $content = '你好!!';
        // $customerService = 'test1@JM68686866';
        if($this->request->isPost()){
            $data = $this->request->post();
            $appid = $data['appid'];
            $openid = $data['openid'];
            $content = $data['content'];
            $customerService = $data['customerService'];
            $author_wx = M('author_wx_user')->where('appid',$appid)->where('authorized',1)->find();
            $wechatObj = new WechatThirdUtil($this->config , $author_wx);
            $result = $wechatObj->appointSendMsgToOne($openid,$content,$customerService);
            if($result){
                echo '成功';
            }else{
                echo '失败';
            }
        }
    }

    public function butt(){
        $butt = M('csuser')->where('auid',33)->where('type',1)->column('id,online_butt');
        if(empty($butt)){
            return true;
        }
        $openid = 'oAtXb0RLyUGwxV25kiZ1LhiPjrM0';
        //先判断用户是否已经有对接客服
        $butt_id = M('users')->where('openid',$openid)->value('butt_id');
        if($butt_id){
            //已有对接客服,把消息传到对应客服
            $post_arr = [
                'content'=>'你好', //消息文本
                'openid'=>'ouW8T0t-nV4GjaSCwbcGMSU0Vgdc', //用户openid
                'appid'=>'wx684cccbe844d934c', //对应公众号appid
                'cs_id'=>$butt_id, //客服id
            ];
            $return = httpRequest('https://a.cnshuangqing.cn/receiveMsg','POST',$post_arr);
            file_put_contents('./requestMsg.log',$return);
        }else{
            //初次对话
            $min_acc = min($butt);
            foreach($butt as $ko=>$vo){
                if($vo == $min_acc){
                    $butt_id = $ko; //获取对接最少客服id
                    break;
                }
            }

            $update_butt_id = M('users')->where('openid',$openid)->update(['butt_id' => $butt_id, 'create_butt_time' => time() , 'groupid' => 1]); //修改客户对接客服id
            $online_butt = M('csuser')->where('id',$butt_id)->update(['online_butt' => $butt[$butt_id]++]);//修改客服在线对接数
            if($update_butt_id && $online_butt){
                $post_arr = [
                    'content'=>'你好', //消息文本
                    'openid'=>'ouW8T0t-nV4GjaSCwbcGMSU0Vgdc', //用户openid
                    'appid'=>'wx684cccbe844d934c', //对应公众号appid
                    'cs_id'=>$butt_id, //客服id
                ];
                $return = httpRequest('https://a.cnshuangqing.cn/receiveMsg','POST',$post_arr);
                file_put_contents('./requestMsg.log',$return);
            }else{
                return json(['msg'=>'系统出错']);
            }
        }
    }

    public function getButtInfo($butt_id){
        if(!empty($butt_id)){
            $result = M('users')->where('butt_id',$butt_id)->select();
            return json(['status'=>1,'msg'=>$result]);
        }else{
            return json(['status'=>0,'msg'=>'错误']);
        }
    }

    public function json_de(){
        $json = '{"authorization_info":{"authorizer_appid":"wx570bc396a51b8ff8","authorizer_access_token":"10_oj8AokSO2rM9JgxdJh-4HGT6mDOH4-AFQCG9oy_I1V3gKisTUg-vBNqf3HFQ014IDlU8Tx5pMOz2cf6VgygEtbciIP6UvcEzbatjp5iCzNg_MmpSeYaMyW_SpXfEBLWLUEf_HgR3YVQl0q3KVRSeAKDBXY","expires_in":7200,"authorizer_refresh_token":"refreshtoken@@@hL3_Kr9GuyjQFiXWDCGMeABmKTqRQL7uwsFDt8El7Jk","func_info":[{"funcscope_category":{"id":1}},{"funcscope_category":{"id":15}},{"funcscope_category":{"id":4}},{"funcscope_category":{"id":7}},{"funcscope_category":{"id":2}},{"funcscope_category":{"id":3}},{"funcscope_category":{"id":11}},{"funcscope_category":{"id":6}},{"funcscope_category":{"id":5}},{"funcscope_category":{"id":8}},{"funcscope_category":{"id":13}},{"funcscope_category":{"id":9}},{"funcscope_category":{"id":10}},{"funcscope_category":{"id":12}},{"funcscope_category":{"id":17}},{"funcscope_category":{"id":18},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":19}},{"funcscope_category":{"id":22}},{"funcscope_category":{"id":23}},{"funcscope_category":{"id":24},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":25},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":26}},{"funcscope_category":{"id":27},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":30},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":31},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":33},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":35}},{"funcscope_category":{"id":36}},{"funcscope_category":{"id":37}},{"funcscope_category":{"id":40}}]}}';
        $wdata = json_decode($json,true);
        dump($wdata);
    }

    public function tag(){
        $appid = 'wx283f05dbb353b933';
        $author_wx = M('author_wx_user')->where('appid',$appid)->where('authorized',1)->find();
        dump($author_wx);
        $wechatObj = new WechatThirdUtil($this->config , $author_wx);
        $tag_result = $wechatObj->createGroups('abc');
        dump($tag_result);
    }
}